/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controle;

import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.AtorDAO;

/**
 *
 * @author ThaísRamir
 */
public class Ator extends javax.swing.JFrame {

    /**
     * Creates new form CadastroAtor
     */
    public Ator() {
        initComponents();
        jtbConsultaModel =  (DefaultTableModel) jtbConsulta.getModel();
        
        
      
        
          
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jfAtor = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jbCadastrarAtor3 = new javax.swing.JButton();
        jbAlterar = new javax.swing.JButton();
        jbExcluir = new javax.swing.JButton();
        jbConsultar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbConsulta = new javax.swing.JTable();
        jlId = new javax.swing.JLabel();
        jfId = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
        jLabel1.setText("Ator:");

        jfAtor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jfAtorActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Comic Sans MS", 1, 18)); // NOI18N
        jLabel2.setText("Cadastrar Ator");

        jbCadastrarAtor3.setText("Cadastrar");
        jbCadastrarAtor3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCadastrarAtorActionPerformed(evt);
            }
        });

        jbAlterar.setText("Alterar");
        jbAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAlterarActionPerformed(evt);
            }
        });

        jbExcluir.setText("Excluir");
        jbExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbExcluirActionPerformed(evt);
            }
        });

        jbConsultar.setText("Consultar");
        jbConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbConsultarActionPerformed(evt);
            }
        });

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Contatos"));

        jtbConsulta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nome do ator", "Id"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtbConsulta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jtbConsultaMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jtbConsulta);

        jlId.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
        jlId.setText("Id:");

        jfId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jfIdActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbCadastrarAtor3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(jlId)))
                        .addGap(10, 10, 10)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jfId, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jbConsultar)
                            .addGap(26, 26, 26)
                            .addComponent(jbAlterar)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jbExcluir))
                        .addComponent(jfAtor, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 480, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jLabel2))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlId, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jfAtor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbCadastrarAtor3, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jtbConsultaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbConsultaMouseReleased
        int linhaSelecionada = jtbConsulta.getSelectedRow(); //retorna um inteiro
        jfId.setText(jtbConsulta.getValueAt(linhaSelecionada, 1).toString());
        jfAtor.setText(jtbConsulta.getValueAt(linhaSelecionada, 2).toString());

    }//GEN-LAST:event_jtbConsultaMouseReleased

    private void jbConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbConsultarActionPerformed
        // TODO add your handling code here:
        if( jfAtor.getText().isEmpty() ){ //se o campo está vazio
            JOptionPane.showMessageDialog(rootPane, "Nome inválido!");
        }
        else{
            ArrayList<modelo.Ator> atores = ator_dao.consultar(jfAtor.getText());
            if(atores.isEmpty()){ //se há registros no banco de dados para a chave consultada
                JOptionPane.showMessageDialog(rootPane, "O contato não está cadastrado.");
            }
            else{
                //preencher a tabela, inclui:
                excluirLinhasNaTabela(); //excluir linhas na tabela atual
                incluirLinhasNaTabela(atores); //incluir linhas na tabela para que elas possam receber os dados da consulta atual
                preencherTabela(atores); //colocar os valores nas linhas
                preencherTabela(atores);
            }
        }
    }//GEN-LAST:event_jbConsultarActionPerformed

    private void jbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExcluirActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jbExcluirActionPerformed

    private void jbAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlterarActionPerformed
        // TODO add your handling code here:

    }//GEN-LAST:event_jbAlterarActionPerformed

    private void jbCadastrarAtorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCadastrarAtorActionPerformed
        // TODO add your handling code here:

        ator.setNome_ator(jfAtor.getText());
        ator_dao.inserir(ator);

    }//GEN-LAST:event_jbCadastrarAtorActionPerformed

    private void jfIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jfIdActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jfIdActionPerformed

    private void jfAtorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jfAtorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jfAtorActionPerformed

    
    private void excluirLinhasNaTabela(){
        int qdeDeLinhas = jtbConsultaModel.getRowCount(); //a quantidade de linhas deve ser obtida antes de removê-las
        for (int cont=0; cont < qdeDeLinhas; cont++){ //sempre utilize a técnica de controle por contador e utilize como limite a quantidade de linhas presente na tabela (antes da remoção) 
            jtbConsultaModel.removeRow(0); //sempre remova a linha ZERO
    
        }
      }
         private void incluirLinhasNaTabela(ArrayList<Ator> atores){
        Object[] linha = new Object[5]; //cria um array de objetos com o tamanho da quantidade de campos (colunas) da tabela
        for(int c=0; c < atores.size(); c++){
            jtbConsultaModel.addRow(linha); //adiciona linhas na tabela até o tamanho do arrayList (que contém os dados de uma consulta do tipo listar)
        }
    }
          private void preencherTabela(ArrayList<Ator> atores){
        //adiciona os valores da consulta nas linhas da tabela
        int row = 0;        
        for (Ator ator : atores) { //usa um for-each para percorrer o arrayList e alimentar a camada de modelo da JTable 
            jtbConsultaModel.setValueAt(ator.getCod_ator(), row, 1);
            jtbConsultaModel.setValueAt(ator.getNome_ator(), row, 0);
           
           
            row++;
        }  
    }
    
    public void limparCampos(){
    
    jfAtor.setText("");
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ator().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbAlterar;
    private javax.swing.JButton jbCadastrarAtor3;
    private javax.swing.JButton jbConsultar;
    private javax.swing.JButton jbExcluir;
    private javax.swing.JTextField jfAtor;
    private javax.swing.JTextField jfId;
    private javax.swing.JLabel jlId;
    private javax.swing.JTable jtbConsulta;
    // End of variables declaration//GEN-END:variables
 Ator ator = new Ator();
 AtorDAO ator_dao = new AtorDAO();
 DefaultTableModel jtbConsultaModel;
  
   
}

